import axios from 'axios';

const API_URL = 'http://localhost:9090';

// 创建 service 实例
const service = axios.create({
    baseURL: API_URL,
    timeout: 5000
});

// 请求拦截器：自动添加 token 到 headers（登录/注册除外）
service.interceptors.request.use(config => {
    const publicPaths = ['/user/login', '/user/register'];
    if (!publicPaths.includes(config.url)) {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
    }
    return config;
}, error => {
    return Promise.reject(error);
});

export default {
    // 登录接口
    login(userInfo) {
        return service.post('/user/login', {
            username: userInfo.username,
            password: userInfo.password
        });
    },

    // 注册接口
    register(userInfo) {
        return service.post('/user/register', {
            username: userInfo.username,
            password: userInfo.password,
            permission: userInfo.permission || 0,
            adminKey: userInfo.adminKey || ''
        });
    },

    // 获取窗口内的所有点：武汉
    getPoints(minX, minY, maxX, maxY) {
        return service.get('/poi/window/wuhan', {
            params: { minX, minY, maxX, maxY }
        });
    },

    // 获取窗口内的所有点：社区
    getPointsCommunity(minX, minY, maxX, maxY) {
        return service.get('/poi/window/community', {
            params: { minX, minY, maxX, maxY }
        });
    },

    // 查询待审核的街景点
    getPointsExamine() {
        return service.get('/poi/examine');
    },

    // 获取图片（返回预签名URL）
    getImageByPid(pid) {
        return service.get(`/image/get/${pid}`);
    },

    // 获取评论通过pid
    getCommentsByPid(pid) {
        return service.get(`/comment/${pid}`);
    },

    // 添加评论
    uploadComment(pid, content, username) {
        return service.post('/comment/upload', {
            pid: pid,
            content: content,
            username: username
        });
    },

    getImagesByPid(pid) {
        return service.get(`/image/get/${pid}`);
    },

    // 添加新的 Point
    addPoint(pointData) {
        return service.post('/poi/add', {
            pid: pointData.pid,
            longitude: pointData.longitude,
            latitude: pointData.latitude,
            name: pointData.name || '',
            username: pointData.username || ''
        });
    },

    // 上传图片
    uploadImage(file, pid) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('pid', pid);
        return service.post('/image/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
    },

    // 删除评论
    deleteComment(cid) {
        return service.delete('/comment/delete', {
            params: { cid }
        });
    }
};
